package com.leve.control.service;

import com.leve.control.constant.ErrorCode;
import com.leve.control.domain.BackUser;
import com.leve.control.mapper.BackUserMapper;
import com.leve.control.util.MD5Util;
import com.leve.control.util.Result;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author whongyu
 * @create by 2019/6/12
 */
@Service
public class BackUserService {

    @Resource
    private BackUserMapper backUserMapper;

    /**
     * 系统用户登录接口
     * @param userName
     * @param password
     * @return
     */
    public Result login(String userName, String password){
        Map<String ,Object> map = new HashMap<>();
        map.put("userName",userName);
        List<BackUser> users = backUserMapper.findUser(map);
        if(users.size() > 0 && users != null){
            String password1 = MD5Util.fromStringToMD5(password);
            map.put("password",password1);
            List<BackUser> users1 = backUserMapper.findUser(map);
            if(users1.size() > 0 && users1 != null){
                BackUser backUser = users1.get(0);
                return new Result(ErrorCode.SUCCESS,backUser);
            }else {
                return new Result(ErrorCode.E_20008);//密码不正确
            }
        }else {
            return new Result(ErrorCode.E_20007);//用户名不存在
        }
    }


    public int addBackUser(BackUser backUser){
        String s = MD5Util.fromStringToMD5(backUser.getPassword());
        backUser.setPassword(s);
        backUser.setCreateTime(new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
        return backUserMapper.addBackUser(backUser);
    }

    /**
     * 编辑用户 包含密码修改
     * @param backUser
     * @return
     */
    public int updateBackUser(BackUser backUser){
        BackUser user = backUserMapper.findById(backUser.getUserId());
        if(!user.getPassword().equals(backUser.getPassword())){
            String s = MD5Util.fromStringToMD5(backUser.getPassword());
            backUser.setPassword(s);
        }
        return backUserMapper.update(backUser);
    }

    public int removeBackUser(int userId){
        return backUserMapper.remove(userId);
    }

    public List<BackUser> findBackUser(BackUser backUser){
        Map<String,Object> map = new HashMap<>();
        map.put("userName",backUser.getUserName());
        return backUserMapper.findUser(map);
    }
}
